package jsu.weizixuan.likesystem.job;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import jsu.weizixuan.likesystem.mapper.BlogMapper;
import jsu.weizixuan.likesystem.mapper.ThumbMapper;
import jsu.weizixuan.likesystem.model.msg.ThumbEvent;
import jsu.weizixuan.likesystem.model.pojo.Blog;
import jsu.weizixuan.likesystem.model.pojo.Thumb;
import jsu.weizixuan.likesystem.service.ThumbService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * @Title: TransactionalMethod
 * @Author 魏子轩
 * @Package jsu.weizixuan.likesystem.job
 * @Date 2025/9/28 11:11
 * @description: 添加事务的方法
 */
@Service
@RequiredArgsConstructor
public class TransactionalMethod {

    private final BlogMapper blogMapper;
    private final ThumbService thumbService;
    private final ThumbMapper thumbMapper;

    @Transactional(rollbackFor = Exception.class)
    public void batchUpdateBlogs(Map<Long, Long> countMap) {
        if (!countMap.isEmpty()) {
            blogMapper.batchUpdateThumbCount(countMap);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void batchInsertThumbs(List<Thumb> thumbs) {
        if (!thumbs.isEmpty()) {
            // 分批次插入
            thumbService.saveBatch(thumbs, 500);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void doThumbMethod(ThumbEvent thumbEvent){
        blogMapper.update(
                new LambdaUpdateWrapper<Blog>()
                        .setSql("thumbCount = thumbCount + 1")
                        .eq(Blog::getId, thumbEvent.getBlogId())
        );
        thumbMapper.insert(
                new Thumb().setBlogId(thumbEvent.getBlogId()).setUserId(thumbEvent.getUserId())
        );
    }

    @Transactional(rollbackFor = Exception.class)
    public void undoThumbMethod(ThumbEvent thumbEvent){
        blogMapper.update(
                new LambdaUpdateWrapper<Blog>()
                        .setSql("thumbCount = thumbCount - 1")
                        .eq(Blog::getId, thumbEvent.getBlogId())
        );
        thumbMapper.delete(
                new LambdaUpdateWrapper<Thumb>()
                        .eq(Thumb::getBlogId, thumbEvent.getBlogId())
                        .eq(Thumb::getUserId, thumbEvent.getUserId())
        );
    }
}
